package cqrtplm.service.impl;


import com.ty.basic.handler.exceptionhandler.exception.TyException;
import cqrtplm.dto.OrderChangeDTO;
import cqrtplm.entity.OrderChangeDetail;
import cqrtplm.entity.OrderChangeHeader;
import cqrtplm.entity.OrderChangeMaterial;
import cqrtplm.mapper.OrderChangeDetailMapper;
import cqrtplm.mapper.OrderChangeHeaderMapper;
import cqrtplm.mapper.OrderChangeMaterialMapper;
import cqrtplm.service.OrderChangeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.UUID;

@Service
public class OrderChangeServiceImpl implements OrderChangeService {

    @Autowired
    private OrderChangeHeaderMapper headerMapper;

    @Autowired
    private OrderChangeDetailMapper detailMapper;

    @Autowired
    private OrderChangeMaterialMapper materialMapper;


    @Override
    @Transactional
    public void create(OrderChangeDTO dto) throws Exception {
        // 1. 检查 header 是否为空
        if (dto.getHeader() == null) {
            throw new IllegalStateException("Header cannot be null");
        }

        // 2. 获取前端传入的 oid
        String oid = dto.getHeader().getOid();
        if (oid == null || oid.trim().isEmpty()) {
            throw new IllegalStateException("OID is required for creation");
        }

        // 【可选】3. 检查该 oid 是否已存在（防止重复提交）
        OrderChangeHeader existing = headerMapper.selectByOid(oid);
        if (existing != null) {
            throw new IllegalStateException("OID already exists: " + oid);
        }

        // 4. 直接使用前端传的 oid，不再生成
        // （dto.getHeader().setOid(oid); 已包含在 dto 中，无需再设）

        // 5. 插入主表
        headerMapper.insert(dto.getHeader());

        // 6. 插入子表，关联同一个 oid
        if (dto.getDetails() != null && !dto.getDetails().isEmpty()) {
            for (OrderChangeDetail d : dto.getDetails()) {
                d.setOid(oid);
                detailMapper.insert(d);
            }
        }

        if (dto.getMaterials() != null && !dto.getMaterials().isEmpty()) {
            for (OrderChangeMaterial m : dto.getMaterials()) {
                m.setOid(oid);
                materialMapper.insert(m);
            }
        }
    }
    @Override
    @Transactional
    public void update(OrderChangeDTO dto) {
        String oid = dto.getHeader().getOid();

        detailMapper.deleteByOid(oid);
        materialMapper.deleteByOid(oid);

        headerMapper.update(dto.getHeader());

        if (dto.getDetails() != null && !dto.getDetails().isEmpty()) {
            for (OrderChangeDetail d : dto.getDetails()) {
                d.setOid(oid);
                detailMapper.insert(d);
            }
        }

        if (dto.getMaterials() != null && !dto.getMaterials().isEmpty()) {
            for (OrderChangeMaterial m : dto.getMaterials()) {
                m.setOid(oid);
                materialMapper.insert(m);
            }
        }
    }

    @Override
    public OrderChangeDTO getByOid(String oid) {
        OrderChangeHeader header = headerMapper.selectByOid(oid);
        if (header == null) {
            return null;
        }

        OrderChangeDTO dto = new OrderChangeDTO();
        dto.setHeader(header);
        dto.setDetails(detailMapper.selectByOid(oid));
        dto.setMaterials(materialMapper.selectByOid(oid));
        return dto;
    }

    // OrderChangeServiceImpl.java

    @Override
    @Transactional
    public void delete(String oid) throws Exception {
        // 可选：先检查是否存在
        OrderChangeHeader existing = headerMapper.selectByOid(oid);
        if (existing == null) {
            throw new IllegalStateException( "要删除的记录不存在，OID: " + oid);
        }

        // 只需删除主表，子表由 Oracle 级联删除
        int deleted = headerMapper.deleteByOid(oid);
        if (deleted == 0) {
            throw new IllegalStateException( "删除失败，可能记录已被其他事务删除");
        }
    }
}